# -*- coding:utf-8 -*-
import socket
import re
import StringIO
import time

pcl = re.compile(r"Content-Length: (.+?)\r\n")

def process(ip, request, port=80):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    sock.sendall(request)
    head = ""
    body = ""
    body_len = 0
    while True:
        t = sock.recv(4096)
        if "\r\n\r\n" in t:
            loc = t.find("\r\n\r\n")
            head += t[:loc]
            body += t[loc+4:]
            break
        else:
            head += t            
    loc = head.find("\r\n")
    line = head[:loc]
    head = head[loc+2:]  

    headers = {}
    
    for h in head.split("\r\n"):
        t = h.split(":")
        headers[t[0]] = t[1].strip()
        
    body_len = int(headers["Content-Length"])
    while (body_len!=len(body)):
        body += sock.recv(4096)
    sock.close()
    return headers, body
    
def send(username, password, uid, content): 
    get_str = """GET %s HTTP/1.1
Connetion: keep-alive
Host: 3g.sina.com.cn

""" % '/prog/wapsite/sso/login.php?ns=1'
    _, body = process("3g.sina.com.cn",get_str)

    url = body.split('<go href="')[1].split('"')[0]
    vk = body.split('name="vk" value="')[1].split('"')[0]
        
    password_field = "password_" + vk.split("_")[0]
    data = "mobile=%s&" % username + password_field + "=%s&vk=" % password + vk + "&submit=1"
    post_str = """POST /prog/wapsite/sso/%s HTTP/1.1
Connetion: keep-alive
HOST: weibo.cn
Content-Length: %d 
Content-Type: application/x-www-form-urlencoded
Referer: http://3g.sina.com.cn/

%s
""" % (url, len(data),data)
    gsid = process("3g.sina.com.cn", post_str)[0]["Set-Cookie"][13:53]
    url = "/dpool/ttt/msgDeal.php?gsid=%s" % (gsid)
    data = """-----------------------------163872102519038996981006397891
Content-Disposition: form-data; name="act"

send
-----------------------------163872102519038996981006397891
Content-Disposition: form-data; name="rl"

0
-----------------------------163872102519038996981006397891
Content-Disposition: form-data; name="uid"

%s
-----------------------------163872102519038996981006397891
Content-Disposition: form-data; name="content"

%s
-----------------------------163872102519038996981006397891
Content-Disposition: form-data; name="attachment"; filename=""
Content-Type: application/octet-stream


-----------------------------163872102519038996981006397891--""" % (uid, content)

    post_str = """POST %s HTTP/1.1
Connetion: keep-alive
Host: weibo.cn
Content-Type: multipart/form-data; boundary=---------------------------163872102519038996981006397891
Content-Length: %d
Referer: http://weibo.cn/dpool/ttt/msgDeal.php

%s
""" % (url, len(data),data)
    process("weibo.cn", post_str)[1].decode("utf-8")
t = time.time()
send("洪瑞琦","19910216","2391847145", "此私信发自微博私信发送工具")
print time.time() - t
